/*
 * @lc app=leetcode.cn id=892 lang=typescript
 *
 * [892] 三维形体的表面积
 */

// @lc code=start

// TODO 表面积涉及到中间凹陷的情况，较难
function surfaceArea(grid: number[][]): number {
    const getAround = (x: number, y: number) => {
        return [
            [x - 1, y],
            [x + 1, y],
            [x, y + 1],
            [x, y - 1],
        ].map(([x, y]) => grid?.[y]?.[x] || 0);
    };
    let sum = 0;
    // 柱状求解法，减去周围被覆盖的范围
    grid.forEach((row, y) => {
        row.forEach((item, x) => {
            if (item === 0) return;
            sum += item * 4 + 2;
            getAround(x, y).forEach((i) => {
                sum -= Math.min(i, item);
            });
        });
    });
    return sum;
}
// @lc code=end
